<template>
  <div v-loading="loading" class="common_list_container">
    <px-radio-group v-model="areaValue" @change="radioChange">
      <px-radio-button v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
    </px-radio-group>
    <px-checkbox-group v-model="filter" class="mt-4 mb-4" @change="handleCheckChange">
      <px-checkbox-button v-for="item in filterList" :key="item.value" :label="item.value">
        {{ item.label }}
      </px-checkbox-button>
    </px-checkbox-group>
    <px-descriptions class="mb-4" :column="4" border>
      <px-descriptions-item v-for="(item, index) in filterNextTimeList" :key="index">
        <template #label>
          <div class="cell-item">{{ item.label }}</div>
        </template>
        下次更换时间：{{ item.value.split(" ")[0] }}
      </px-descriptions-item>
    </px-descriptions>
    <div ref="objectModelTableRef" v-loading="tableLoading" class="table-content">
      <px-table :data="tableData" size="small" border class="common-table" height="calc(100vh - 329px)">
        <!-- <px-table-column label="序号" width="60" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column> -->
        <px-table-column prop="area" label="区域" />
        <px-table-column prop="group" label="组" min-width="100">
          <template #default="scope">
            <div
              v-for="(item, index) in getGroups(scope.row)"
              :key="index"
              class="filter_bro flex flex-col justify-center"
              :style="{ minHeight: `${24 * Object.keys(getGroupsValue(scope.row)[index]).length}px` }"
            >
              {{ item }}
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="filterCode" label="化滤类型" min-width="150">
          <template #default="scope">
            <div v-for="(filters, index) in getGroupsValue(scope.row)" :key="index" class="filter_bro">
              <div v-for="(filter, index) in Object.keys(filters)" :key="index" class="filter_bro">
                {{ filter }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="startTime" label="上次更换时间" min-width="120">
          <template #default="scope">
            <div v-for="(filters, index) in getGroupsValue(scope.row)" :key="index" class="filter_bro">
              <div
                v-for="(filter, index) in Object.values(filters)"
                :key="index"
                class="filter_bro"
                style="color: #3b82f6; cursor: pointer"
                @click="goPms(filter.filterOrderNoOld)"
              >
                {{ filter.startTime?.split(" ")[0] || "-" }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="endTime" label="本次安装时间" min-width="120">
          <template #default="scope">
            <div v-for="(filters, index) in getGroupsValue(scope.row)" :key="index" class="filter_bro">
              <div
                v-for="(filter, index) in Object.values(filters)"
                :key="index"
                class="filter_bro"
                style="color: #3b82f6; cursor: pointer"
                @click="goPms(filter.filterOrderNo)"
              >
                {{ filter.endTime?.split(" ")[0] || "-" }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="lifecycleExp" label="预计寿命" min-width="120">
          <template #default="scope">
            <div v-for="(filters, index) in getGroupsValue(scope.row)" :key="index" class="filter_bro">
              <div v-for="(filter, index) in Object.values(filters)" :key="index" class="filter_bro">
                {{ filter.lifecycleExp || "-" }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="nextInstallDate" label="预计下次更换时间" min-width="120">
          <template #default="scope">
            <div v-for="(filters, index) in getGroupsValue(scope.row)" :key="index" class="filter_bro">
              <div v-for="(filter, index) in Object.values(filters)" :key="index" class="filter_bro">
                {{ filter.nextInstallDate?.split(" ")[0] || "-" }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="nextInstallMonth" label="距离下次更换剩余月" min-width="120">
          <template #default="scope">
            <div v-for="(filters, index) in getGroupsValue(scope.row)" :key="index" class="filter_bro">
              <div v-for="(filter, index) in Object.values(filters)" :key="index" class="filter_bro">
                {{ getNextInstallMonth(filter.nextInstallMonth) }}
              </div>
            </div>
          </template>
        </px-table-column>
      </px-table>
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "FFULedger"
});
import { PxMessage } from "px-ui";
import { queryChildByTypeCodeAndItemValue } from "@/api/common";
import { getListFFUHistory } from "@/api/modules/operation";
import { onMounted, ref } from "vue";
import { getToken } from "@/utils/auth";
import { useRouter } from "vue-router";

const router = useRouter();

const areaList = ref([]);
const areaValue = ref("");
const loading = ref(false);
// 获取区域列表
const queryAreaList = async () => {
  areaList.value = [];
  const res: any = await queryChildByTypeCodeAndItemValue({
    typeCode: "FAB_AREA"
  });
  areaList.value.push(
    ...res
      .filter(e => e.itemDesc.includes("FFU"))
      .map(e => {
        return { value: e.itemName, label: e.itemName };
      })
  );
  areaValue.value = "LITHO";
};
const filter = ref(["Acid", "Base", "VOC", "RC"]);
const filterList = ref([
  {
    value: "Acid",
    label: "Acid"
  },
  {
    value: "Base",
    label: "Base"
  },
  {
    value: "VOC",
    label: "VOC"
  },
  {
    value: "RC",
    label: "RC"
  }
]);
const tableData = ref([]);
const tableLoading = ref(false);
function getGroups(data: Record<string, any>) {
  console.log(`output->data`, data);
  return Object.keys(data).filter(e => e != "area");
}
function getGroupsValue(data: Record<string, any>) {
  const keys = Object.keys(data).filter(e => e != "area");
  const list = [];
  for (let i = 0; i < keys.length; i++) {
    const group = keys[i];
    data[group];
    list.push({ ...data[group] });
  }
  return list;
}
// function getSingleItem(filters: Record<string, any>, key: string) {
//   const list = Object.values(filters)[0];
//   console.log(`output->list`, list);
//   return list[0][key];
// }
const filterNextTimeList = ref([]);
async function queryData() {
  try {
    loading.value = true;
    filterNextTimeList.value = [];
    const params = {
      areaCode: areaValue.value,
      types: filter.value
    };
    const res = await getListFFUHistory(params);
    if (!res) return;
    const areaName = Object.keys(res[0])[0];
    const data = { area: areaName, ...res[0][areaName] };
    tableData.value = [data];
    for (const key in res[1]) {
      const element = res[1][key];
      filterNextTimeList.value.push({ label: key, value: element });
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
}
const radioChange = () => {
  queryData();
};
const handleCheckChange = val => {
  queryData();
};
onMounted(async () => {
  await queryAreaList();
  queryData();
});
function goPms(data: any) {
  if (!data) {
    PxMessage.warning("未查询到历史工单，请查看历史线下工单表单");
    return;
  }
  const facCode = localStorage.getItem("facCode");
  const accessToken = getToken().accessToken || "";
  router.push({
    path: "/all/equip/epm/task/list",
    query: {
      fullpath: `/pmJob/list?jobId=${data}&jobStatus=COMPLETED&pmType=UNS&status=已完成&ssoToken=${accessToken}&facCode=${facCode}&isHiddenMenu=true`
    }
  });
}
function getNextInstallMonth(num: number) {
  if (num < 0) {
    return "-";
  } else {
    return num;
  }
}
</script>

<style lang="scss" scoped>
.common_list_container {
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;

  .common_page {
    height: 33px;
    padding: 0 !important;
    margin-top: 25px;
    margin-bottom: 0;
  }
}

:deep(.px-table .px-table__header-wrapper th, .px-table .px-table__fixed-header-wrapper th) {
  font-size: 14px !important;
}

.filter_bro ~ .filter_bro {
  border-top: 1px solid #e6e6e6;
}
</style>
